//
//  CameraScanViewController.swift
//  ZhiTing
//
//  Created by zy on 2022/6/2.
//

import UIKit
import swiftScan
import AVFoundation

class CameraScanViewController: LBXScanViewController {
    
    var cameraCallback: ((_ result: QRCodeCameraResultModel) -> ())?

    lazy var navBackBtn: Button = {
        let btn = Button()
        btn.frame.size = CGSize.init(width: 30, height: 30)
        btn.setImage(.assets(.nav_back_white), for: .normal)
        btn.addTarget(self, action: #selector(navPop), for: .touchUpInside)
        btn.contentHorizontalAlignment = .left
        return btn
    }()
    
    private lazy var tipsLabel = Label().then {
        $0.textColor = .custom(.white_ffffff)
        $0.font = .font(size: 14, type: .medium)
        $0.text = "请扫描设备机身或底部的二维码".localizedString
        $0.textAlignment = .center
        $0.numberOfLines = 0
    }

    lazy var picBtn: Button = {
        let btn = Button()
        btn.frame.size = CGSize.init(width: 60, height: 60)
        btn.setImage(.assets(.scanImg_icon), for: .normal)
        btn.addTarget(self, action: #selector(openCam), for: .touchUpInside)
        return btn
    }()
    
    lazy var lightBtn: Button = {
        let btn = Button()
        btn.frame.size = CGSize.init(width: 60, height: 60)
        btn.setImage(.assets(.scanLight_off), for: .normal)
        btn.setImage(.assets(.scanLight_on), for: .selected)
        btn.addTarget(self, action: #selector(openLight), for: .touchUpInside)
        return btn
    }()
    
    //手电筒显示状态标识
    var isLightOn = false
    var device = AVCaptureDevice.default(for: .video)

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //需要识别后的图像
        setNeedCodeImage(needCodeImg: true)

        //框向上移动10个像素
        scanStyle?.centerUpOffset += 10
        scanStyle?.animationImage = UIImage(named: "CodeScan.bundle/qrcode_scan_light_green")
        scanStyle?.color_NotRecoginitonArea = UIColor.black.withAlphaComponent(0.8)
        scanStyle?.anmiationStyle = .LineMove
        // Do any additional setup after loading the view.
        
        
        view.addSubview(tipsLabel)
        tipsLabel.frame.size.width = (Screen.screenWidth - 30)
        tipsLabel.frame.size.height = tipsLabel.text!.height(thatFitsWidth: Screen.screenWidth - 30, font: .font(size: 14, type: .medium))
        tipsLabel.frame.origin.x = 15
        tipsLabel.frame.origin.y += (Screen.screenHeight / 2) + 75
        
        view.addSubview(picBtn)
        picBtn.frame.origin.x = (Screen.screenWidth - 60)/2 - 100
        picBtn.frame.origin.y += Screen.screenHeight - 180
        
        view.addSubview(lightBtn)
        lightBtn.frame.origin.x = (Screen.screenWidth - 60)/2 + 100
        lightBtn.frame.origin.y += Screen.screenHeight - 180
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        setupNavigation()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        view.bringSubviewToFront(tipsLabel)
        view.bringSubviewToFront(picBtn)
        view.bringSubviewToFront(lightBtn)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        view.endEditing(true)
        navigationController?.navigationBar.backgroundColor = .custom(.white_ffffff)
        navigationController?.navigationBar.barTintColor = .custom(.white_ffffff)
        navigationController?.navigationBar.tintColor = .custom(.white_ffffff)
    }

    override func handleCodeResult(arrayResult: [LBXScanResult]) {

        for result: LBXScanResult in arrayResult {
            if let str = result.strScanned {
                print(str)
            }
        }

        let result: LBXScanResult = arrayResult[0]

        print(result)
        
        if let resStr = result.strScanned, let model = QRCodeCameraResultModel.deserialize(from: resStr), resStr.contains("ACT"){
            if isLightOn { // 关闭闪光灯
                openLight()
            }
            cameraCallback?(model)
            self.navigationController?.popViewController(animated: true)
            
        } else {
            if let window = SceneDelegate.shared.window {
                ScanFailTipsView.show(to: window) { [weak self] in
                    self?.startScan()
                }
            }
        }
        
    }
    
    @objc func openCam() {
        openPhotoAlbum()
    }
    
    
    @objc func openLight(){
        isLightOn = !isLightOn
        lightBtn.isSelected = isLightOn
        
        do{
               //锁定设备以便进行手电筒状态修改
               try device?.lockForConfiguration()
               if isLightOn{
                   //设置手电筒模式为亮灯（On）
                   device?.torchMode = .on
               }else{
                   //设置手电筒模式为关灯（Off）
                   device?.torchMode = .off
               }
               //解锁设备锁定以便其他APP做配置更新
               device?.unlockForConfiguration()
           }catch{
               return
           }
    }

}

// MARK: - Navigation stuff
extension CameraScanViewController: UIGestureRecognizerDelegate {
    private func setupNavigation() {
        navigationController?.setNavigationBarHidden(false, animated: true)
        
        let navigationBarAppearance = UINavigationBarAppearance()
        navigationBarAppearance.configureWithTransparentBackground()
        navigationBarAppearance.shadowImage = UIImage()
        
        navigationBarAppearance.backgroundColor = .black
        navigationBarAppearance.titleTextAttributes = [NSAttributedString.Key.font: UIFont.font(size: 18, type: .bold), NSAttributedString.Key.foregroundColor: UIColor.custom(.black_3f4663)]
        
        navigationController?.navigationBar.scrollEdgeAppearance = navigationBarAppearance
        navigationController?.navigationBar.standardAppearance = navigationBarAppearance

        navigationController?.interactivePopGestureRecognizer?.delegate = self
        if navigationController?.children.first != self {
            navigationItem.leftBarButtonItem = UIBarButtonItem(customView: navBackBtn)
        }
        
        
        
    }

    @objc func navPop() {
        navigationController?.popViewController(animated: true)
    }
    
    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }
    
}


extension CameraScanViewController {
      
    private class QRCodeResultModel: BaseModel {
        var qr_code = ""
        var url = ""
        var area_name = ""
        var area_id: Int64?
    }
    
}

class QRCodeCameraResultModel: BaseModel {
    var ACT = ""
    var ID = ""
    var DT = ""
    var WiFi = ""
}

